package controller.api;

import com.alibaba.fastjson.JSONObject;
import pojo.Cart;
import service.ICartService;
import service.IUserService;
import service.impl.CartServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AppendToCartServlet", value = "/api/append-to-cart")
public class AppendToCartServlet extends HttpServlet {
    private ICartService cartService;
    private IUserService userService;

    @Override
    public void init() throws ServletException {
        cartService = new CartServiceImpl();
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int uid = userService.queryIdByUsername(request.getParameter("username"));
        int gid = Integer.parseInt(request.getParameter("goods-id"));
        int addCount = Integer.parseInt(request.getParameter("add-count"));
        Map<String, Boolean> map = new HashMap<>();
        map.put("isSuccess", cartService.insertToCart(new Cart(uid, gid, addCount)));
        response.getWriter().write(JSONObject.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
